﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Collections;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ProtoGame.GameLib.Entities
{
    public class Animator
    {
        struct AnimationStateData
        {
            public readonly ushort StartingIndex;
            public readonly ushort EndingIndex;
            public readonly SpriteEffects Effects;
            public readonly TimeSpan ChangeFrame;
            public readonly bool Loop;

            public AnimationStateData(ushort startingIndex, ushort endingIndex, SpriteEffects effects, TimeSpan changeFrame, bool loop)
            {
                StartingIndex = startingIndex;
                EndingIndex = endingIndex;
                Effects = effects;
                ChangeFrame = changeFrame;
                Loop = loop;
            }
        }

        Stopwatch stopwatch = new Stopwatch();
        SortedList<int, AnimationStateData> animations = new SortedList<int, AnimationStateData>();

        byte? currentState = null;
        ushort currentIndex;

        public void AddStaticAnimation(byte state, ushort index)
        {
            AddAnimation(state, index, index, SpriteEffects.None, TimeSpan.Zero, false);
        }

        public void AddAnimation(byte state, ushort startingIndex, ushort endingIndex, SpriteEffects effects, TimeSpan changeFrame, bool loop)
        {
            animations[state] = new AnimationStateData(startingIndex, endingIndex, effects, changeFrame, loop);
        }

        public ushort getAnimationFrame(byte state)
        {
            AnimationStateData stateData = animations[state];

            // Se o estado atual não for igual ao recebido, reinicia animação no novo estado
            if (currentState != state)
            {
                currentIndex = stateData.StartingIndex;
                if (stateData.ChangeFrame != TimeSpan.Zero)
                {
                    stopwatch.Reset();
                    stopwatch.Start();
                }

                currentState = state;
            }
            else if (stateData.ChangeFrame != TimeSpan.Zero)
            {
                if (stopwatch.Elapsed >= stateData.ChangeFrame)
                {
                    if (currentIndex < stateData.EndingIndex)
                        currentIndex++;
                    else if (stateData.Loop)
                        currentIndex = stateData.StartingIndex;
                    
                    stopwatch.Reset();
                    stopwatch.Start();
                }
            }

            return currentIndex;
        }
    }
}
